package main

import (
	"fmt"
	"github.com/labstack/echo/v4"
	"log"
	"net/http"
	"time"
)

// main
//
//	@Description: cookie的crud
func main() {
	e := echo.New()

	e.GET("/cookie/w", WriteCookie)
	e.GET("/cookie/r", ReadCookie)
	e.GET("/cookie/ra", ReadAllCookie)
	e.GET("/cookie/e", ExpiresCookie)

	err := e.Start(":80")
	if err != nil {
		log.Fatal("启动失败")
		return
	}

}

// WriteCookie 写cookie
//
//	@Description:
//	@param c
//	@return error
func WriteCookie(c echo.Context) error {
	cookie := new(http.Cookie)
	cookie.Name = "uid"
	cookie.Value = fmt.Sprintf("%d", time.Now().UnixMilli())
	cookie.Expires = time.Now().Add(time.Second * 120) //过期时间
	c.SetCookie(cookie)
	return c.String(http.StatusOK, "success")

}

// ReadCookie 读取cookie
//
//	@Description:
//	@param c
//	@return error
func ReadCookie(c echo.Context) error {
	cookie, err := c.Cookie("uid")
	if err != nil {
		return c.String(http.StatusOK, err.Error())
	}
	name := cookie.Name
	value := cookie.Value
	sprintf := fmt.Sprintf("cookie  name=%v value=%v", name, value)
	return c.String(http.StatusOK, sprintf)
}

// ExpiresCookie 过期cookie
//
//	@Description:
//	@param c
//	@return error
func ExpiresCookie(c echo.Context) error {
	cookie, err := c.Cookie("uid")
	if err != nil {
		return c.String(http.StatusOK, "cookie not found")
	}
	cookie.Expires = time.Now() //过期时间
	c.SetCookie(cookie)
	return c.String(http.StatusOK, "cookie deleted")
}

// ReadAllCookie 读取所有的cookie
//
//	@Description:
//	@param c
//	@return error
func ReadAllCookie(c echo.Context) error {
	cookies := c.Cookies()
	cookieSlice := make([]string, 0)
	for _, cookie := range cookies {
		name := cookie.Name
		value := cookie.Value
		sprintf := fmt.Sprintf("%v=%v", name, value)
		cookieSlice = append(cookieSlice, sprintf)
	}
	return c.JSON(http.StatusOK, cookieSlice)
}
